package com.zhong.test_12;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DML {
    /**
     * 实现增删改的操作
     * 需要先调用setConnection方法
     *
     * @param *sql,增删改命令
     * @param *params sql命令中的参数
     */
    private static Connection con;
    private static PreparedStatement pst;

    public static void setConnection(Connection con) {
        DML.con = con;
    }

    //private static Connection con;
    public static void update(String sql, Object... params) {
        try {
            pst = con.prepareStatement(sql);//创建预编译声明对象

            //给 sql 命令注入参数
            for (int i = 0; i < (params == null ? -1 : params.length); i++) {
                pst.setObject(i + 1, params[i]);
            }
            //发送并执行命令
            //设置事务为显示事务
            con.setAutoCommit(false);
            int result = pst.executeUpdate();
            if (result == 0) System.out.println("执行失败！");
            else {
                System.out.println("执行成功！");
                //提交事务
                con.commit();
            }

        } catch (SQLException sqlException) {
            //命令执行失败，回滚事务
            try {
                con.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            sqlException.printStackTrace();
        } finally {
            DBUtils.release(con, pst, null);
        }
    }
}
